"""
Test module to assert the performance of retrieving an auto-installation file.
"""

import gc
import os
from typing import Callable

import pytest
from pytest_benchmark.fixture import (  # type: ignore[reportMissingTypeStubs,import-untyped]
    BenchmarkFixture,
)

from cobbler.api import CobblerAPI
from cobbler.autoinstall.manager import AutoInstallationManager
from cobbler.items.distro import Distro

from tests.performance import CobblerTree


@pytest.mark.parametrize(
    "what",
    [
        "profile",
        "system",
    ],
)
@pytest.mark.parametrize(
    "cache_enabled",
    [
        False,
        True,
    ],
)
def test_get_autoinstall(
    benchmark: BenchmarkFixture,
    cobbler_api: CobblerAPI,
    create_distro: Callable[[str, bool], Distro],
    cache_enabled: bool,
    what: str,
):
    """
    Test that asserts if retrieving rendered autoinstallation templates is running without a performance decrease.
    """

    def item_get_autoinstall(api: CobblerAPI, what: str):
        autoinstall_mgr = AutoInstallationManager(cobbler_api)
        for test_item in api.get_items(what):
            autoinstall_mgr.generate_autoinstall(test_item, test_item.autoinstall)  # type: ignore
        gc.collect()

    # Arrange
    iterations = 1
    if CobblerTree.test_iterations > -1:
        iterations = CobblerTree.test_iterations
    iterations_per_test = int(
        os.getenv("COBBLER_PERFORMANCE_TEST_GET_AUTOINSTALL_ITERATIONS", -1)
    )
    if iterations_per_test > -1:
        iterations = iterations_per_test
    cobbler_api.settings().cache_enabled = cache_enabled
    cobbler_api.settings().enable_menu = False
    CobblerTree.create_all_objs(
        cobbler_api, create_distro, save=False, with_triggers=False, with_sync=False
    )

    # Act
    result = benchmark.pedantic(  # type: ignore
        item_get_autoinstall,
        rounds=CobblerTree.test_rounds,
        iterations=iterations,
        args=(cobbler_api, what),
    )

    # Assert
